<template>
  <view>
    <view class="home_detail">
      <uni-list>
        <uni-list-item title="门店名称" link :rightText="storeName"></uni-list-item>
        <uni-list-item title="门店位置" link :rightText="storeAddress"></uni-list-item>
        <uni-list-item title="分类管理" link :rightText="typeCount!=''?typeCount+'个分类':''"></uni-list-item>
        <uni-list-item title="设备管理" link :rightText="deviceCount!=''?deviceCount+'台设备':''" @tap="gotoDeviceList(storeId)">
        </uni-list-item>
      </uni-list>
      <view class="home_user">门店成员</view>
    </view>
    <scroll-view scroll-y="true" :style="'height:'+ clientHeight+'px;'">
      <uni-list v-for="(item,index) in userList" :key="index">
        <uni-list-item :title="item.nickName" :note="item.phonenumber" showArrow
          :thumb="item.avatar==null||item.avatar==''?avatar:baseUrl+item.avatar" 
          thumb-size="lg" :rightText="item.isadmin==1?'管理员':''" @tap="setStoreUser(item.equipmentStoreNo,item.isadmin,item.userId)"></uni-list-item>
      </uni-list>
    </scroll-view>
    <view class="btn_baocun" style="margin-top: 10rpx;min-height: 90rpx;">
      <button type="warn" v-if="isSharer==0" @tap="exitShare" style="width: 80%;background-color: #ff976a;height: 80rpx;
         line-height: 80rpx;">退出门店共享
         </button>
    </view>
  </view>
</template>

<script>
  import {getStore,updateStore,delStore} from '@/api/system/store/store.js'
  import {getStoreShareUsers,setAdmin,delShareRecord, setIsAdmin} from '@/api/system/store/shareRecord.js'
   import config from '@/config'
  export default {
    data() {
      return {
        storeName: "",
        storeAddress: "",
        typeCount:"",
        deviceCount:"",
        userId: uni.getStorageSync("userId"),
        queryParams: {
          equipmentStoreNo: null,
           shareType: 1
        },
        userList: [],
        storeId: '',
        isSharer:null,
        clientHeight: 0,
        baseUrl: config.baseUrl,
        avatar:"https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0"
      }
    },
    onLoad(option) {
      this.storeId=option.storeId
      this.isSharer=option.isSharer
      if(option.type==1){
         uni.setNavigationBarTitle({
              title: '我的共享门店详细' // 新标题
            });
      }else{
        uni.setNavigationBarTitle({
             title: '我收到的共享门店详细' // 新标题
           });
      }
      //查询门店详细
      this.getStoreDetaile()
      //查询分享用户
      this.getShareUser()
    },
    onShow() {
      var that = this;
      uni.getSystemInfo({
        success: function(res) {
          let screenHeight = uni.getSystemInfoSync().windowHeight //获取屏幕高度
          // 通过query 获取其余盒子的高度
          let query = uni.createSelectorQuery().in(that)
          query.select(".home_detail").boundingClientRect()
          query.select(".btn_baocun").boundingClientRect()
          //通过query.exec返回的数组 进行减法 同时 去除margin 和border的
          query.exec(res => {
            let h1 = res[0].height
            let h2 = res[1].height
            let scrollHeight = screenHeight - h1 - h2 - 70
            that.clientHeight = scrollHeight
          })
        }
      })
    },
    methods: {
      //查询们的详细
      getStoreDetaile(){
        getStore(this.storeId).then(response => {
           if(response.code==200){
            let maps = new Map();
            this.storeName = response.data.storeName;
            this.storeAddress = response.data.storeAddress
            this.deviceCount =response.data.mkEquipments.length
            this.latitude = response.data.lat
            this.longitude = response.data.lon
            //获取类型数量去重
            this.typeCount=(response.data.mkEquipments.map(itme=>({
              id:parseInt(itme.equipmentTypeId),
              name:itme.mkEquipmentType.equipmentTypeName
            })).filter((v)=>!maps.has(v.id)&& maps.set(v.id,1))).length
           }
        })
      },
      //查询分享的门店成员包括自己
      getShareUser(){
        this.queryParams.equipmentStoreNo=this.storeId
        getStoreShareUsers(this.queryParams).then(response => {
          if(response.code == 200){
            uni.stopPullDownRefresh()
            this.userList=response.rows
          }
        })
      },
      //跳转设备列表
      gotoDeviceList(storeId){
        this.$tab.navigateTo("/devicelistpkg/deviceManage/deviceList?storeId="+storeId)
      },
      //设置管理员或删除门店成员
    setStoreUser(equipmentStoreNo,isadmin,userId) {
        if(this.isSharer==1){
        if(userId!=this.userId){
          var thant = this;
          uni.showActionSheet({
            alertText: "请选择",
            itemList: [isadmin==1?'设置为普通成员':'设置为管理员', '删除'],
            success: (res) => {
              switch (res.tapIndex) {
                case 0:
                  uni.showModal({
                    title: '提示',
                    content: isadmin==1?'确定设置该成员为普通成员吗？':'确定设置该成员为管理员吗？',
                    success: function(res) {
                      if (res.confirm) {
                        try {
                          const data={
                            equipmentStoreNo:equipmentStoreNo,
                            isadmin:isadmin==1?0:1,
                            recipientId:userId
                          } 
                          setIsAdmin(data).then(response => {
                            if(response.code == 200){
                               uni.showToast({
                                 title: '设置成功',
                                 duration: 1500,
                                 success: function() {
                                   //查询门店成员
                                   thant.getShareUser()
                                 }
                               })
                            }
                          })
                        } catch (err) {
                          thant.$modal.msgError(err.msg);
                        }
                      }
                    }
                  })
                  break;
                case 1:
                  uni.showModal({
                    title: '提示',
                    content: '确定删除该门店成员吗？',
                    success: function(res) {
                      if (res.confirm) {
                        try {
                          const data={
                             equipmentStoreNo:thant.storeId,
                             recipientId:thant.userId
                          }
                          delShareRecord(data).then(response => {
                            if(response.code == 200){
                               uni.showToast({
                                 title: '退出成功',
                                 duration: 1500,
                                 success: function() {
                                   //查询门店成员
                                   thant.getShareUser()
                                 }
                               })
                            }
                          })
                        } catch (err) {
                          thant.$modal.msgError(err.msg);
                        }
                      }
                    }
                  })
                  break;
              }
            },
            fail(error) {
              thant.$modal.msgError(error);
            }
          })
        }else{
           this.$modal.showToast("分享者本人不能设置和删除自己");
        }
        }
      },
      //退出分享门店
      exitShare(){
        var thant = this;
        uni.showModal({
            title: '确定退出该分享门店吗？',
            content: '退出该分享的门店后将无法控制此门店下的所有设备',
            success: function(res) {
              if (res.confirm) {
                try {
                  const data={
                    equipmentStoreNo:thant.storeId,
                    recipientId:thant.userId
                  }
                  delShareRecord(data).then(response => {
                    if (response.code == 200) {
                      uni.navigateBack({
                        delta: 1,
                        success: (res) => {
                          if (res.errMsg = "navigateBack:ok") {
                            thant.$modal.msgSuccess("退出成功");
                          }
                        },
                      })
                    }
                  })
                } catch (err) {
                  thant.$modal.msgError(err.msg);
                }
              }
            }
        })
      },
    },
    //下拉刷新
    onPullDownRefresh() {
      this.getShareUser()
    }
  }
</script>

<style>
  page {
    background-color: #f9f9f9;
  }

  .home_detail {
    margin-top: 56rpx;
    width: 92%;
    margin: 56rpx auto;
  }

  ::v-deep .home_detail .uni-list-item__extra-text {
    font-size: 32rpx;
    overflow: hidden;
    text-align: right;
    vertical-align: middle;
    width: 300rpx;
  }

  .home_user {
    margin: 30rpx 0 30rpx 30rpx;
    font-size: 28rpx;
    color: #acacac;
  }
  .add_user{
    width: 80%;height: 80rpx;line-height: 80rpx;
  }
</style>